package com.qf.service;
import com.qf.domain.TbUser;
import com.qf.mapper.TbUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private TbUserMapper sysUserMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        TbUser sysUser = sysUserMapper.loginByUsername(username);
        if(sysUser == null){
            throw new UsernameNotFoundException("用户不存在");
        }
        // 查询用户权限
        Set<String> strings = sysUserMapper.selectByUserId(sysUser.getId());
        // 将权限数据放入claims,用于存入jwt
        Set<GrantedAuthority> authorities = new HashSet<>();
        strings.forEach(item->{
            authorities.add(new SimpleGrantedAuthority(item));
        });
        // 查询用户角色权限
        Set<String> roles = sysUserMapper.selectByUserIdV2(sysUser.getId());
        // 将角色权限数据放入claims,用于存入jwt
        roles.forEach(item->{
            authorities.add(new SimpleGrantedAuthority("ROLE_"+item));
        });
        // 返回用户信息,包括用户名、密码、权限集合(既有用户权限，也有角色权限)
        return new User(sysUser.getUsername(),sysUser.getPassword(), authorities);

    }
}

